import datetime

from core import ts_download, ts_merge


class down():
    def __init__(self,ts_lists,key,path,name,retrynum,threadnum = 0,):
        self.key = key
        self.path = path
        self.ts_lists = ts_lists
        self.name = name
        self.retrynum = retrynum #重试的次数
        self.retry_list = []    #需要重下的列表
        self.threadnum = threadnum #线程数，0则自动分配

    def download(self):
        key = self.key
        tsurl_list = self.ts_lists

        state = True
        if self.threadnum==0:
            state = False
            print("自动分配线程数")
            self.threadnum = self.autothreadnum(tsurl_list)

        this_ts_download = ts_download.ts_download(tsurl_list, self.path, self.threadnum, key)
        start = datetime.datetime.now().replace(microsecond=0)
        self.retry_list = this_ts_download.mul_thread_download()
        for i in range(self.retrynum):
            if len(self.retry_list):
                if state==False:
                    num = self.autothreadnum(self.retry_list)
                that_ts_download = ts_download.ts_download(self.retry_list, self.path, num, key)
                self.retry_list = that_ts_download.mul_thread_download()
        if len(self.retry_list)==0:
            print("全部下载完成")
        else:
            print("下列ts下载失败")
            for ts in self.retry_list:
                print(ts)
        end = datetime.datetime.now().replace(microsecond=0)

        s = "下载用时：" + str(end - start)
        print(s)
        return self.retry_list

    def autothreadnum(self,tsurl_list) -> int:
        """
        自动生成线程数
        :param tsurl_lists:ts下载地址列表 
        :param path:下载地址
        :return: 线程数
        """
        n = len(tsurl_list)
        n = (int)(n / 20) + 1
        if n <= 32:
            return n
        else:
            return 32


    def combine(self):
        start = datetime.datetime.now().replace(microsecond=0)
        this_merge = ts_merge.ts_megre(self.path, self.name, self.threadnum)
        path_list = this_merge.build_catalog()
        this_merge.move(path_list)
        this_merge.combine()
        this_merge.del_catalog(path_list)
        this_merge.del_file()
        end = datetime.datetime.now().replace(microsecond=0)
        s = "合并用时：" + str(end - start)
        print(s)